const Stock = require('../models/Stock');
const TencentStockService = require('./TencentStockService');
const LevelDBService = require('./LevelDBService');

class StockService {
  constructor() {
    // 模拟股票数据库
    this.stocks = new Map();
    this.initializeSampleData();
  }

  // 初始化示例数据
  initializeSampleData() {
    const sampleStocks = [
      new Stock('000001', '平安银行', 15.00, new Date()),
      new Stock('600000', '浦发银行', 10.00, new Date()),
      new Stock('600036', '招商银行', 40.00, new Date()),
      new Stock('600519', '贵州茅台', 1500.00, new Date()),
      new Stock('000858', '五粮液', 200.00, new Date())
    ];

    sampleStocks.forEach(stock => {
      this.stocks.set(stock.symbol, stock);
    });
  }

  // 获取所有股票
  getAllStocks() {
    return Array.from(this.stocks.values()).map(stock => stock.getInfo());
  }

  // 根据代码获取股票
  getStockBySymbol(symbol) {
    const stock = this.stocks.get(symbol);
    return stock ? stock.getInfo() : null;
  }

  // 更新股票价格
  updateStockPrice(symbol, newPrice) {
    const stock = this.stocks.get(symbol);
    if (stock) {
      stock.updatePrice(newPrice);
      return stock.getInfo();
    }
    return null;
  }

  // 添加新股票
  addStock(symbol, name, currentPrice) {
    if (this.stocks.has(symbol)) {
      throw new Error('Stock with this symbol already exists');
    }
    
    const newStock = new Stock(symbol, name, currentPrice, new Date());
    this.stocks.set(symbol, newStock);
    return newStock.getInfo();
  }

  // 从真实API获取股票数据
  async getRealStockData(symbol) {
    try {
      const realData = await TencentStockService.getRealTimeData(symbol);
      
      // 更新本地数据
      if (this.stocks.has(symbol)) {
        this.updateStockPrice(symbol, realData.price);
      } else {
        this.addStock(symbol, realData.name, realData.price);
      }
      
      // 将股票名称缓存到数据库
      await this.cacheStockName(symbol, realData.name);
      
      return realData;
    } catch (error) {
      throw new Error(`Failed to fetch real stock data: ${error.message}`);
    }
  }

  // 获取多只股票的实时数据
  async getMultipleRealStockData(symbols) {
    try {
      const realData = await TencentStockService.getMultipleStocks(symbols);
      
      // 更新本地数据
      realData.forEach(stock => {
        if (stock.error) return; // 跳过有错误的股票
        
        if (this.stocks.has(stock.symbol)) {
          this.updateStockPrice(stock.symbol, stock.price);
        } else {
          this.addStock(stock.symbol, stock.name, stock.price);
        }
      });
      
      // 将股票名称缓存到数据库
      for (const stock of realData) {
        if (!stock.error) {
          await this.cacheStockName(stock.symbol, stock.name);
        }
      }
      
      return realData;
    } catch (error) {
      throw new Error(`Failed to fetch multiple real stock data: ${error.message}`);
    }
  }

  // 将股票名称缓存到数据库
  async cacheStockName(symbol, name) {
    try {
      // 检查数据库中是否已存在该股票
      let stock = await LevelDBService.getStockBySymbol(symbol);
      
      if (stock) {
        // 如果股票已存在但名称不同，则更新名称
        if (stock.name !== name) {
          const stockId = stock.id;
          stock = await LevelDBService.getStockById(stockId);
          stock.name = name;
          await LevelDBService.updateStockName(stockId, name);
        }
      } else {
        // 如果股票不存在，则创建新股票记录
        await LevelDBService.createStock(symbol, name);
      }
    } catch (error) {
      console.error(`Failed to cache stock name for ${symbol}:`, error.message);
    }
  }

  // 模拟市场价格变动
  simulatePriceChanges() {
    this.stocks.forEach(stock => {
      // 随机价格波动 (-2% 到 +2%)
      const changePercent = (Math.random() - 0.5) * 4;
      const newPrice = stock.currentPrice * (1 + changePercent / 100);
      stock.updatePrice(parseFloat(newPrice.toFixed(2)));
    });
  }
}

module.exports = new StockService(); // 单例模式